package com.yhb.conf;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.log4j.Log4j;
import lombok.var;
import me.edzh.spring.bootstrap.utils.JSONUtil;
import me.edzh.spring.bootstrap.utils.exception.ServiceException;
import org.apache.commons.lang3.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

@Log4j
public class Configuration {
    public final static String KEY_CONFIG = "config-yhbConfig";

    private static Map<String, Object> sConfigMap = new HashMap<>();
    private final static Map<String, ConfigItem> defaults = new HashMap<String, ConfigItem>() {{
        put(ConfigKey.INVITE_VIP_AVAILABLE.name(), new ConfigItem<>(ConfigKey.INVITE_VIP_AVAILABLE.name(), true));
        put(ConfigKey.CALC_GRAND_FATHER_ACTIVATE_BONUS.name(), new ConfigItem<>(ConfigKey.CALC_GRAND_FATHER_ACTIVATE_BONUS.name(), true));
    }};

    public static void setConfigMap(Map<String, Object> configMap) {
        sConfigMap = ObjectUtils.defaultIfNull(configMap, sConfigMap);
        log.warn("configRefreshed:" + JSONUtil.toJson(sConfigMap));
    }

    public static <T> T getConfig(ConfigKey key, Class<T> clazz) {
        var result = defaults.get(key.name()).get(sConfigMap);
        if (clazz.isAssignableFrom(result.getClass())) {
            return clazz.cast(result);
        }

        throw new ServiceException(ResultCode.ERROR_INTERNAL_DATA_CODE, "internal err");
    }

    public enum ConfigKey {
        INVITE_VIP_AVAILABLE,
        CALC_GRAND_FATHER_ACTIVATE_BONUS
    }

    @Data
    @AllArgsConstructor
    private static class ConfigItem<T> {
        private String key;
        private T defaultValue;

        public T get(Map<String, Object> configMap) {
            if (configMap == null) return defaultValue;

            if (!configMap.containsKey(key)) return defaultValue;

            try {
                return (T)configMap.get(key);

            } catch (Throwable t) {
                return defaultValue;
            }
        }
    }
}
